package com.itheima.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @author Tang
 * @date 2023/4/12
 */
//对象处理器，自动填充字段
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 新增数据时，会执行该方法
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("执行新增--自动填充字段");
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        //通过session获取当前系统登录的用户id
        //Long employeeId = (Long) session.getAttribute("employeeId");
        //优化: 使用ThreadLocal获取id
        Long employeeId = BaseContext.getValue();
        metaObject.setValue("createUser", employeeId);
        metaObject.setValue("updateUser", employeeId);
    }

    /**
     * 更新操作时，会执行该方法
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("MyMetaObjectHandler:当前线程id={}",Thread.currentThread().getId());
        log.info("更新操作--自动填充字段");
        metaObject.setValue("updateTime", LocalDateTime.now());
        //通过session获取当前系统登录的用户id
        //Long employeeId = (Long) session.getAttribute("employeeId");
        //优化: 使用ThreadLocal获取id
        Long employeeId = BaseContext.getValue();
        metaObject.setValue("updateUser", employeeId);
    }
}
